package ah.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;

/**
 * mysql front导出的sql,blob写成文件
 * @author dhding
 *
 */
public class MysqlBlobToFile {

	/**
	 * id, blob, postfix
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new FileReader("c:/result.sql"));
		File dir = new File("c:/result");
		if (!dir.exists()) {
			dir.mkdir();
		}
		String line = null;
		while ( (line = br.readLine()) != null) {
			if (line.startsWith("INSERT INTO")) {
				int index = line.indexOf("VALUES (");
				line = line.substring(index + "VALUES (".length());
				String[] vals = line.split(",");
				
				line = vals[1].substring(2, vals[1].length()-1);
				
				byte[] b = hex2byte(line);
				FileOutputStream fos = new FileOutputStream(new File(dir, vals[0] + vals[2].substring(1, vals[2].length()-3)));//保存的文件名
				fos.write(b);
				fos.close();
			}
		}
	
	}
	
	
	/**  
	 * 格式化byte(图片二进制转字符串)  
	 *   
	 * @param b  
	 * 
	 * @return  
	 */  
	public static String byte2hex(byte[] b) {   
	    char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',   
	            'B', 'C', 'D', 'E', 'F' };   
	    char[] out = new char[b.length * 2];   
	    for (int i = 0; i < b.length; i++) {   
	        byte c = b[i];   
	        out[i * 2] = Digit[(c >>> 4) & 0X0F];   
	        out[i * 2 + 1] = Digit[c & 0X0F];   
	    }  
	    return new String(out);   
	} 
	

	public static byte[] hex2byte(String s) {   
	    byte[] src = s.toLowerCase().getBytes();   
	    byte[] ret = new byte[src.length / 2];   
	    for (int i = 0; i < src.length; i += 2) {  
	        byte hi = src[i];   
	        byte low = src[i + 1];   
	       hi = (byte) ((hi >= 'a' && hi <= 'f') ? 0x0a + (hi - 'a')   
	                : hi - '0');   
	        low = (byte) ((low >= 'a' && low <= 'f') ? 0x0a + (low - 'a')   
	                : low - '0');
	        ret[i / 2] = (byte) (hi << 4 | low);   
	    }   
	    return ret;   
	} 
}
